﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Lipesin.BuildUpdateLaunch
{
	/// <summary>
	/// Структура папки назначения
	/// </summary>
	public class FileIndex
	{
		private List<IndexedFile> _files = new List<IndexedFile>();
		public List<IndexedFile> Files { get { return _files; } }

		public FileIndex() { }
		public FileIndex(Stream stream)
		{
			BinaryFormatter formatter = new BinaryFormatter();
			_files = formatter.Deserialize(stream) as List<IndexedFile>;
		}

		public void Write(Stream stream)
		{
			BinaryFormatter formatter = new BinaryFormatter();
			formatter.Serialize(stream, _files);
		}

		public void Rebuild(string rootPath)
		{
			foreach (DirectoryInfo subdir in new DirectoryInfo(rootPath).GetDirectories())
				IndexDirectory(subdir);
		}
		private void IndexDirectory(DirectoryInfo directory)
		{
			foreach (FileInfo file in directory.GetFiles())
				IndexFile(file);
			foreach (DirectoryInfo subdir in directory.GetDirectories())
				IndexDirectory(subdir);
		}
		private void IndexFile(FileInfo file)
		{
			string lowerName = file.Name.ToLower();
			IndexedFile found = _files.SingleOrDefault(item => item.Name == lowerName);
			if (found == null)
			{
				found = new IndexedFile();
				found.Name = lowerName;
				_files.Add(found);
			}
			found.PathDestination.Add(file.DirectoryName);
		}
	}

	/// <summary>
	/// Еденичный копируемый файл
	/// </summary>
	[Serializable]
	public class IndexedFile
	{
		public IndexedFile()
		{
			PathDestination = new List<string>();
		}
		public string Name { get; set; }
		public List<string> PathDestination { get; set; }
	}
	/// <summary>
	/// Еденичный копируемый файл с путём - источником
	/// </summary>
	public class IndexedFileWithSource : IndexedFile
	{
		public IndexedFileWithSource(IndexedFile file, string pathSource)
		{
			Name = file.Name;
			PathDestination = file.PathDestination;
			PathSource = pathSource;
		}
		public string PathSource { get; set; }
	}
}
